
const xpcom = require("xpcom");
const widgeon = require("widgeon");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

function TempStoreStreamListener () {};
TempStoreStreamListener.prototype = {
    classDescription:   "Temporarily stores widgets that come off the network",
    classID:            Components.ID("{2fb0ba94-c269-4679-96ae-5aa32b7f52da}"),
    contractID:         "@berjon.com/temp-store-sl;1",
    // _xpcom_categories:  [{ category: "external-uricontentlisteners"}],
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener]),

    file:       null,
    _stream:    null,
    onStartRequest: function (req, ctx) {
        var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
        var sugName = req.name ? req.name.replace(/^.*\//, "") : "widget.wgt";
        file.append(Date.now() + "-" + sugName);
        file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
        this.stream = Cc["@mozilla.org/network/safe-file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
        this.stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate
        this.file = file;
    },
    onStopRequest: function (req, ctx, status) {
        this.stream instanceof Ci.nsISafeOutputStream ? this.stream.finish() : this.stream.close();
        widgeon.handleDownloadedWidget(this.file).open();
        this.file.remove();
    },
    onDataAvailable: function (req, ctx, is, offset, cnt) {
        var bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
        bstream.setInputStream(is);
        var bytes = bstream.readBytes(cnt);
        this.stream.write(bytes, cnt);
        bstream.close();
    }
};
xpcom.register({
    create:     TempStoreStreamListener,
    name:       TempStoreStreamListener.prototype.classDescription,
    contractID: TempStoreStreamListener.prototype.contractID,
    uuid:       TempStoreStreamListener.prototype.classID
});



function AppWidgetMediaType () {}
AppWidgetMediaType.prototype = {
    classDescription:   "Handles the application/widget media type",
    classID:            Components.ID("{c2c24288-139c-4320-8949-b4308eccae6a}"),
    contractID:         "@berjon.com/application-widget;1",
    // _xpcom_categories:  [{ category: "external-uricontentlisteners"}],
    QueryInterface:     XPCOMUtils.generateQI([Ci.nsIURIContentListener, Ci.nsISupportsWeakReference]),
    
    loadCookie:            null,
    parentContentListener:  null,

    canHandleContent:    function (type, pref, dType) {
        // console.log("canHandleContent: " + type);
        if (type === "application/widget") return true;
        return false;
    },
    
    doContent:    function (type, pref, req, cntHandler) {
        cntHandler.value = Cc["@berjon.com/temp-store-sl;1"].createInstance(Ci.nsIStreamListener);
        return false; // or maybe we'll handle it ourselves instead?
    },

    isPreferred:    function (type, dType) {
        if (type === "application/widget") return true;
        return false;
    },
    
    onStartURIOpen:    function (uri) {
        // console.log("onStartURIOpen: " + uri.spec);
        return false;
    },
};

xpcom.register({
    create:     AppWidgetMediaType,
    name:       AppWidgetMediaType.prototype.classDescription,
    contractID: AppWidgetMediaType.prototype.contractID,
    uuid:       AppWidgetMediaType.prototype.classID
});

var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(Ci.nsIURILoader);
var appWid = Cc["@berjon.com/application-widget;1"].createInstance(Ci.nsIURIContentListener);
uriLoader.registerContentListener(appWid);

var catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
catMan.addCategoryEntry("ext-to-type-mapping", "wgt", "application/widget", true, true);

